import React from 'react';
import {Button, Card, Form, Input, Select, Modal, Checkbox, message,Icon,Row,Col} from 'antd';
import jQuery from "jquery";

const CheckboxGroup = Checkbox.Group;
const Option = Select.Option;
const FormItem = Form.Item;

const sendTitleText = "主题发送";
const sendTitle = 1;
const sendLinkText = "链接发送";
const sendLink = 2;
const sendTypeIdx={
    "主题发送":sendTitle,
    "链接发送":sendLink
};

// 结尾组件
class GroupMessage extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            ModalVisible: false,
            showSendLink: false,
            GroupCheckedList: [],
            GroupAllList: [],             //不是模态框中的所有群
            ModalGroupAllList:[],        //模态框中的所有所有群
            GroupClassificationMap:[],  //保存分组的下拉选对象以及 每个分组有哪些group
            GroupClassification:[],     //保存分组的下拉选对象只有分组
            ModalGroupNameVisible:true //是否显示模态框中的分组名称
        }
    }

    componentDidMount() {
        this.findAllGroup(false);
        this.groupClassification();
    }

    //处理群分类
    groupClassification=()=>{

        let me = this;

        fetch('/snail/group/findGroupClassification', {
            method: "GET",
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
        }).then(function (response) {
            response.json().then(function (data) {
                let children = [];
                data = data.data;
                me.setState({
                    GroupClassificationMap:data
                });
                children.push(<Option key="全部">全部</Option>);
                for (let i = 0; i < data.length; i++) {
                    children.push(<Option key={data[i].name}>{data[i].name}</Option>);
                }
                me.setState({
                    GroupClassification:children
                });
                //设置默认的分组
                me.props.form.setFieldsValue({
                    groupType: children[0].key,
                })
            })
        }, function (error) {
            console.log("error:",error);
        })
    };
    /*
    *   isModal 是否为模态框
    * */
    //处理返回所有群
    findAllGroup=(isModal)=>{
        let me = this;
        //获取所有群
        fetch('/snail/group/findAllGroup', {
            method: "GET",
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
        }).then(function (response) {
            response.json().then(function (data) {
                data = data.data.pageInfo.list;
                let groupList = [];
                let checkList = [];
                for (var i = 0; i < data.length; i++) {
                    groupList.push({
                        label: data[i].groupName,
                        value: data[i].groupName+","+data[i].hookUrl
                    });
                    checkList.push(data[i].groupName+","+data[i].hookUrl)
                }
                //设置模态框中的所有群
                if(isModal){
                    me.setState({
                        ModalGroupAllList:groupList
                    })
                }else{
                    me.setState({
                        GroupAllList: groupList,
                        GroupCheckedList: checkList
                    });
                }
                me.props.form.setFieldsValue({
                    sendType: sendTitleText,
                })
            })
        }, function (error) {
            console.log("error:",error);
        })
    };
    //发送群消息
    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (!err) {
                console.log('Received values of form: ', values);
            }
        });

        // let me = this;
        // let data = this.props.form.getFieldsValue();
        // let urlArr = [];
        // data["sendType"] = sendTypeIdx[data["sendType"]];
        // //添加群到分组的时候无法获取label的值把label和url拼接在一起
        // for(let i = data.webhookURL.length-1;i>=0;i--){
        //     if(data["webhookURL"][i]!=undefined){
        //         urlArr.push(data["webhookURL"][i].split(",")[1]);
        //     }
        // }
        // data.webhookURL = urlArr;
        // console.log("dataaaaaaa",data);
        // fetch('/snail/attendence/groupNotification', {
        //     method: "POST",
        //     headers: {
        //         'Accept': 'application/json',
        //         'Content-Type': 'application/json'
        //     },
        //     body: JSON.stringify(data)
        // }).then(function (response) {
        //     response.json().then(function (data) {
        //         if (data.code == 200) {
        //             message.info(data.data);
        //         }
        //         me.groupClassification();
        //         me.findAllGroup();
        //         me.props.form.setFieldsValue({
        //             webhookURL: []
        //         });
        //     })
        // }).catch((e)=>{
        //      console.log("error",e);
        //     message.info("发送失败");
        //     me.groupClassification();
        //     me.findAllGroup();
        //     me.props.form.setFieldsValue({
        //         webhookURL: []
        //     });
        // })
    };
    //控制复选框是否全选
    checkAll = (checkedValues) => {
        let checked = checkedValues.target.checked;
        console.log("GroupCheckedList",this.state.GroupCheckedList);
        if (checked) {
            this.props.form.setFieldsValue({
                webhookURL: this.state.GroupCheckedList
            })
        } else {
            this.props.form.setFieldsValue({
                webhookURL: []
            })
        }
    };
    //复选框改变
    checkChange = (checkedValues) => {

    };
    //下拉选 发送类型
    handleSelectChange = (value) => {
        if (value == sendTitle) {
            this.setState({
                showSendLink: false
            });
            this.props.form.setFieldsValue({
                sendType: sendTitleText,
            })
        } else if (value == sendLink) {
            this.setState({
                showSendLink: true
            });
            this.props.form.setFieldsValue({
                sendType: sendLinkText,
            })
        }
    };
    //选择群分类显示群信息
    handleGroupTypeChange = (value) => {
        //如何是选择全部 请求findAllGroup
        if(value=="全部"){
            this.findAllGroup(false);
        }
        console.log("value",value);
        this.props.form.setFieldsValue({
            groupType: value,
        });
        let groupMap = this.state.GroupClassificationMap;
        let groupList = [];
        let checkList = [];
        for (let i = 0; i < groupMap.length; i++) {
            if(groupMap[i].name==value) {
                for(let j=0;j<groupMap[i].group.length;j++) {
                    let group = groupMap[i]["group"][j];
                    groupList.push({
                        label: group.groupName,
                        value: group.groupName+","+group.webhookurl
                    });
                    checkList.push(group.groupName+","+group.webhookurl)
                }
            }
        }
        this.setState({
            GroupAllList: groupList,
            GroupCheckedList: checkList
        });
    };
    //点击添加弹出新增的模态框
    handleAddGroupModal=()=>{
        this.setState({
            ModalVisible:true,
            ModalGroupNameVisible:true
        });
        this.findAllGroup(true);
    };
    //删除分组
    handleMinusClassification=()=>{
        let formData = this.props.form.getFieldsValue();
        let param = {};
        let me = this;
        param.classificationName = formData.groupType;
        fetch('/snail/group/deleteClassification', {
            method: "POST",
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: jQuery.param(param)
        }).then(function (response) {
            response.json().then(function (data) {
                if (data.code == 200) {
                    me.groupClassification();
                    me.findAllGroup();
                    me.props.form.setFieldsValue({
                        webhookURL: []
                    });
                    message.info(data.message);
                }
            })
        }, function (error) {
            console.log("error:",error);
        })
    };

    //点击 + 弹出新增模态框
    handlePlusGroupModal=()=>{
        this.setState({
            ModalVisible:true,
            ModalGroupNameVisible:false
        });
        this.findAllGroup(true);
    };
    //删除分组中的群
    handleMinusGroup=()=>{
        let me = this;
        let param=[];
        let data = this.props.form.getFieldsValue();
        console.log("value",data);
        for(let i=0;i<data.webhookURL.length;i++){
            let item = data["webhookURL"][i];
            let obj = {};
            obj.groupName=item.split(",")[0];
            obj.webhookurl=item.split(",")[1];
            obj.groupClassificationName=data.groupType;
            param.push(obj);
        }

        fetch('/snail/group/deleteGroupClassification', {
            method: "POST",
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(param)
        }).then(function (response) {
            response.json().then(function (data) {
                if (data.code == 200) {
                    me.groupClassification();
                    me.findAllGroup();
                    me.props.form.setFieldsValue({
                        webhookURL: []
                    });
                    message.info(data.message);
                }
            })
        }, function (error) {
            console.log("error:",error);
        })
    };

    //保存群到指定的分组当中
    handleAddGroupSubmit=()=>{
        /**
         *  请求参数
         * [{"webhookurl":"addGro","groupName":"ceshifenzy","groupClassificationName":"分组一"},{"webhookurl":"addGroup2Url","groupName":"addGroup2","groupClassificationName":"分组五"}]
         */
        let me = this;
        let formData = this.props.form.getFieldsValue();
        console.log("formData",formData);
        let param = [];
        for(let i=0;i<formData.allGroup.length;i++){
            let groupObj = {};
            let item = formData["allGroup"][i];
            groupObj.groupName = item.split(",")[0];
            groupObj.webhookurl = item.split(",")[1];
            if(formData.groupClassificationName){
                groupObj.groupClassificationName=formData.groupClassificationName;
            }else {
                groupObj.groupClassificationName = formData.groupType;
            }
            param.push(groupObj);
        }
        fetch('/snail/group/saveGroupClassification', {
            method: "POST",
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(param)
        }).then(function (response) {
            response.json().then(function (data) {
                if (data.code == 200) {
                    me.setState({
                        ModalVisible: false
                    });
                    me.groupClassification();
                    me.findAllGroup();
                    me.props.form.setFieldsValue({
                        webhookURL: []
                    });
                    me.props.form.setFieldsValue({
                        allGroup:[]
                    });
                    message.info(data.message);
                }
            })
        }, function (error) {
            console.log("error:",error);
        });
    };

    //隐藏模态框
    handleCancel=()=>{
        this.setState({
            ModalVisible: false
        });
    };
    //搜索群名（选择器方法）：
    handleChange=(value)=>{
        console.log("111:",this.state.GroupAllList);
        console.log("222:",this.state.GroupCheckedList);
        console.log(`selected ${value}`);
    };

    render() {
        console.log("this.props.form:",this.props.form);
        console.log("this.state.form:",this.state.form);
        const {getFieldDecorator} = this.props.form;
        let me = this;
        console.log("你好呀：",this.state.GroupAllList);
        // console.log("hello ya:",this.state.GroupCheckedList);
        return (
            <div>
                <Form horizontal onSubmit={this.handleSubmit}>
                    <Card extra={<Button type="primary" htmlType="submit">发送</Button>}>
                        <Form.Item
                            label="发送类型"
                            labelCol={{span: 6}}
                            wrapperCol={{span: 14}}
                        >
                            {getFieldDecorator('sendType')(
                                <Select id="select" size="large" defaultValue="2"
                                        style={{width: 200}}
                                        onChange={me.handleSelectChange}>
                                    <Option value="1">主题发送</Option>
                                    <Option value="2">链接发送</Option>
                                </Select>
                            )}
                        </Form.Item>
                        <Form.Item
                            label="群分类"
                            labelCol={{span: 6}}
                            wrapperCol={{span: 14}}
                        >
                            {getFieldDecorator('groupType')(
                                <Select id="select" size="large" defaultValue="2" style={{width: 200}}
                                        onChange={me.handleGroupTypeChange}
                                >
                                    {this.state.GroupClassification}
                                </Select>
                            )}
                            <Button type="primary" onClick={me.handleAddGroupModal}>新建</Button>
                            <Button type="primary" onClick={me.handleMinusClassification}>删除</Button>
                        </Form.Item>
                        <Form.Item
                            label="群组"
                            labelCol={{span: 6}}
                            wrapperCol={{span: 14}}
                        >
                            {getFieldDecorator('webhookURL')(
                                <div style={{ width: '1000px',height:"1000px",background:"#ff0",border:"1px solid #0f0" }}>
                                    <Checkbox onChange={me.checkAll}/>
                                    <Select
                                        mode="multiple"
                                        style={{ width: '500px',height:"500px",background:"#ccc",border:"1px solid #f00" }}
                                        placeholder="请输入..."
                                        defaultValue={this.state.GroupCheckedList}
                                        onChange={this.handleChange}
                                    >
                                        {this.state.GroupAllList}123241234154135
                                    </Select>
                                    <CheckboxGroup options={this.state.GroupAllList}
                                                   defaultValue={this.state.GroupCheckedList}/>
                                    <Icon type="plus" onClick={me.handlePlusGroupModal}/>
                                    <Icon type="minus" onClick={me.handleMinusGroup} />
                                </div>
                            )}
                        </Form.Item>
                        <Form.Item
                            label="主题"
                            labelCol={{span: 6}}
                            wrapperCol={{span: 14}}
                            style={{display: this.state.showSendLink ? "block" : "none"}}
                        >
                            {getFieldDecorator('theme')(
                                <Input style={{width: 300}}/>
                            )}
                        </Form.Item>
                        <Form.Item
                            label="正文"
                            labelCol={{span: 6}}
                            wrapperCol={{span: 14}}
                        >
                            {getFieldDecorator('text')(
                                <Input type="textarea" style={{width: 300}}/>
                            )}
                        </Form.Item>
                        <Form.Item
                            label="链接路径"
                            labelCol={{span: 6}}
                            wrapperCol={{span: 14}}
                            style={{display: this.state.showSendLink ? "block" : "none"}}
                        >
                            {getFieldDecorator('linkPath')(
                                <Input style={{width: 300}}/>
                            )}
                        </Form.Item>
                    </Card>
                </Form>
                <Modal title="请选择要添加的群" visible={this.state.ModalVisible}
                       onOk={this.handleAddGroupSubmit} onCancel={this.handleCancel}
                >
                    <Form horizontal onSubmit={this.handleAddGroupSubmit}>
                        <Form.Item
                            label="分类名称"
                            labelCol={{span: 6}}
                            wrapperCol={{span: 14}}
                            style={{display:this.state.ModalGroupNameVisible?"block":"none"}}
                        >
                            {getFieldDecorator('groupClassificationName')(
                                <Input />
                            )}
                        </Form.Item>
                        <Form.Item
                            label="群组"
                            labelCol={{span: 6}}
                            wrapperCol={{span: 14}}
                        >
                            {getFieldDecorator('allGroup')(
                                <CheckboxGroup options={me.state.ModalGroupAllList}/>
                            )}
                        </Form.Item>
                    </Form>
                </Modal>
            </div>
        )
    }
}

const SendGroupMessage = Form.create()(GroupMessage);
export default SendGroupMessage;
